(function() {
  "use strict";

  /**
   * @ngdoc function
   * @name webApp.controller:KefuCtrl
   * @description
   * # KefuCtrl
   * Controller of the webApp
   */
  angular.module("webApp").controller("KefuCtrl", KefuCtrl);

  KefuCtrl.$inject = [
    "$scope",
    "dataService",
    "helper",
    "dhfprinterService",
    "$timeout",
    "$interval",
    "$rootScope",
    "$state",
    "moment",
    "$location",
    "$compile"
  ];

  function KefuCtrl(
    $scope,
    dataService,
    helper,
    dhfprinterService,
    $timeout,
    $interval,
    $rootScope,
    $state,
    moment,
    $location,
    $compile
  ) {
    $scope.listAction = function() {
      $scope.getList();
      // $rootScope.getsubscribe();
    };

    $scope.getList = function() {
      dataService
        .sellerAuthorizeAuthorizer_infoGet($rootScope.store_id)
        .then(function(list) {
          $scope.autorspcfg = [];
          console.error("config list", $scope.autorspcfg);
          if (list) {
            async.map(
              list,
              function(data, callback) {
                var query = { app_id: data.app_id };
                dataService.autorspcfgGet(query).then(function(config) {
                  if (config) {
                    // config.session_reply_info = $scope.parse(config.session_reply_info);
                    // config.rcvmsg_reply_info = $scope.parse(config.rcvmsg_reply_info);
                    config.nick_name = data.nick_name;
                    $scope.autorspcfg.push(config);
                  }
                  callback(null, null);
                });
              },
              function(e, r) {
                // console.error("config list",$scope.autorspcfg);
              }
            );
          }
        });
    };

    $scope.parse = function(str) {
      if (str) {
        str = str ? JSON.parse(str) : "";
        if (str.url && str) {
          // console.error("ddddddddddddd", str);
          // var dt = str.url.split("url=");
          // str.thumb_url = decodeURI(dt[1]);
        }
        return str;
      }
    };

    $scope.delkf = function(id) {
      helper.myConfirm("是否删除此条记录！", function() {
        var data = { kf_id: id };
        dataService.wxkfdel(data).then(function(result) {
          if (result) {
            helper.myAlert("success");
            $scope.getKf();
          } else {
            helper.myAlert("error：" + result.Msg);
          }
        });
      });
    };

    $scope.wxkfaddApi = function() {
      var data = {
        kf_id: $scope.kf.kf_id,
        app_id: $scope.wxapp_id,
        event: $scope.kf.event,
        eventkey: $scope.kf.eventkey,
        desc: $scope.kf.desc,
        eventtype: $scope.kf.eventtype,
        type: "1",
        msgtype: 1,
        tag: $scope.kf.tag,
        msgcode: JSON.stringify($scope.kf.msgcode)
      };
      dataService.wxkfadd(data).then(function(result) {
        if (result.kf_id) {
          helper.myAlert("success", "#/kefu/add?wxapp_id=" + $scope.wxapp_id);
        } else {
          helper.myAlert("error：" + result.Msg);
        }
      });
    };
    $scope.kefuAddphp = function() {
      var data = $scope.kf.msgcode;
      for (var i = data.length - 1; i >= 0; i--) {
        if (data[i].msgtype == "1") {
          if (!data[i].title) {
            helper.myAlert("设置回复内容不能为空");
            return false;
          }
        }
        if (
          data[i].msgtype == "2" ||
          data[i].msgtype == "3" ||
          data[i].msgtype == "4"
        ) {
          if (!data[i].media_id) {
            helper.myAlert("设置回复图片不能为空");
            return false;
          }
        }
        if (data[i].msgtype == "5") {
          if (!data[i].title) {
            helper.myAlert("设置回复内容不能为空");
            return false;
          }
          if (!data[i].pagepath) {
            helper.myAlert("小程序的页面路径不能为空");
            return false;
          }
          if (!data[i].thumb_media_id) {
            helper.myAlert("小程序卡片图不能为空！");
            return false;
          }
        }
      }
      //保存数据
      $scope.wxkfaddApi();
    };
    $scope.addAction = function() {
      $scope.wxapp_id = $location.search().wxapp_id;
      $scope.app_type = $location.search().app_type;
      if ($scope.wxapp_id) {
        $scope.getOne();
      }
    };
    $scope.wxkfaddAction = function() {
      $scope.wxapp_id = $location.search().wxapp_id;
      $scope.kf_id = $location.search().kf_id;
      $scope.msginit = [
        {
          msgtype: "1",
          title: "",
          media_id: "",
          app_id: "",
          pagepath: "",
          imgUrl: "",
          thumb_media_id: ""
        }
      ];
      if ($scope.kf_id) {
        $scope.getKf();
      } else {
        $scope.getKfone();
      }
      console.error($scope.wxapp_id);
    };
    //返回 选择的路径
    $scope.savepath = function(path, submsgcode) {
      if (path) {
        submsgcode.pagepath = path;
      }
    };

    $scope.getOne = function() {
      var query = { app_id: $scope.wxapp_id };
      dataService.autorspcfgGet(query).then(function(config) {
        if (config) {
          if (config.service_type_id == 1) {
            $scope.getKf();
          }
          config.session_reply_info = $scope.parse(config.session_reply_info);
          config.rcvmsg_reply_info = $scope.parse(config.rcvmsg_reply_info);
          config.session_reply_type = config.session_reply_type || "text";
          config.rcvmsg_reply_type = config.rcvmsg_reply_type || "text";
          config.session_reply_open = parseInt(config.session_reply_open);
          config.rcvmsg_reply_open = parseInt(config.rcvmsg_reply_open);
          config.subscribe_reply_open = parseInt(config.subscribe_reply_open)
            ? parseInt(config.subscribe_reply_open)
            : 0;
          config.subscribe_reply_info = $scope.parse(
            config.subscribe_reply_info
          );
          config.subscribe_reply_type = config.subscribe_reply_type || "text";
          $scope.config = config;
          console.error("$scope.config", $scope.config);
        }
      });
    };
    $scope.getKf = function() {
      var query = { app_id: $scope.wxapp_id, kf_id: $scope.kf_id };
      dataService.wxkfget(query).then(function(config) {
        if (config.list) {
          $scope.wxkflist = config.list;
          if ($scope.kf_id) {
            $scope.kf = $scope.wxkflist[0];
            $scope.getKfone();
          }
        }
      });
    };

    $scope.getKfone = function() {
      if ($scope.kf) {
        // $scope.chosedType = $scope.kf.msgtype;
        $scope.kf.msgcode = $scope.parse($scope.kf.msgcode);
        console.log("msgcode====", $scope.kf.msgcode);
      } else {
        $scope.kf = {};
        //初始化值
        $scope.kf.msgcode = clone($scope.msginit);
      }
    };

    $scope.showGzh = function() {
      $scope.loginWin = $.alert({
        backdrop: "static",
        keyboard: false,
        title: '<span >{{"扫码"|translate}}</span>',
        body:
          '<div style="text-align: center;"> <img ng-src="{{gzhimg}}" width="250" style="border: 2px solid;" />  </div>',
        okBtn: '{{"login"|translate}}',
        closeBtn: true,
        hasfoot: false,
        transition: true,
        width: "small",
        show: function(e) {
          $compile($(e.currentTarget).contents())($scope);
        },
        okHide: function(e) {}
      });
    };

    $scope.kefuAdd = function() {
      $scope.inspectData();
      dataService.autorspcfgUpdate($scope.config).then(function(result) {
        if (result.partner_id) {
          helper.myAlert("success", "#/kefu/list");
        } else {
          helper.myAlert("error：" + result.Msg);
        }
      });
    };
    //事件回执
    $scope.eventbackcall = function(data) {
      getgzhimg(data).then($scope.showGzh);
    };

    $scope.addimgurl = function(data, submsgcode, type) {
      if (data) {
        if (type) {
          submsgcode.thumb_media_id = data.media_id;
          submsgcode.media_id = "";
        } else {
          submsgcode.media_id = data.media_id;
          submsgcode.thumb_media_id = "";
        }
      }
    };

    //添加
    $scope.addMsg = function() {
      var msginit = {
        msgtype: "1",
        title: "",
        media_id: "",
        app_id: "",
        pagepath: "",
        imgUrl: "",
        thumb_media_id: ""
      };
      $scope.kf.msgcode.push(msginit);
      console.log("新增规格--->", $scope.kf.msgcode);
    };

    function getgzhimg(data) {
      var data = {
        // "expire_seconds": 604800,
        action_name: "QR_LIMIT_STR_SCENE",
        action_info: {
          scene: {
            scene_str: data
          }
        }
      };
      return dataService
        .wxQrcodeGet($scope.wxapp_id, data)
        .then(function(redata) {
          console.error(redata, $scope.scene_id);
          if (redata) {
            return ($scope.gzhimg = "data:image/png;base64," + redata);
          }
        });
    }

    //检查数据
    $scope.inspectData = function() {
      if ($scope.config.session_reply_info) {
        $scope.config.session_reply_info = $scope.AssembleData(
          $scope.config.session_reply_type,
          $scope.config.session_reply_info
        );
        // $scope.config.session_reply_type == "text" ? $scope.config.session_reply_info = { "content": $scope.config.session_reply_info.content } : $scope.config.session_reply_info = { "media_id": $scope.config.session_reply_info.media_id };
      }
      if ($scope.config.rcvmsg_reply_info) {
        $scope.config.rcvmsg_reply_info = $scope.AssembleData(
          $scope.config.rcvmsg_reply_type,
          $scope.config.rcvmsg_reply_info
        );
        // $scope.config.rcvmsg_reply_type == "text" ? $scope.config.rcvmsg_reply_info = { "content": $scope.config.rcvmsg_reply_info.content } : $scope.config.rcvmsg_reply_info = { "media_id": $scope.config.rcvmsg_reply_info.media_id };
      }

      if ($scope.config.subscribe_reply_info) {
        // $scope.config.subscribe_reply_type == "text" ? $scope.config.subscribe_reply_info = { "content": $scope.config.subscribe_reply_info.content } : $scope.config.subscribe_reply_info = { "media_id": $scope.config.subscribe_reply_info.media_id };
        $scope.config.subscribe_reply_info = $scope.AssembleData(
          $scope.config.subscribe_reply_type,
          $scope.config.subscribe_reply_info
        );
      }
    };
    $scope.AssembleData = function(type, data) {
      if (type == "text") {
        return { content: data.content };
      }
      if (type == "image") {
        return { media_id: data.media_id };
      }
      if (type == "link") {
        return {
          title: data.title,
          description: data.description,
          url:
            "https://qy.dhfapp.com/a.php?url=" +
            encodeURIComponent(data.thumb_url),
          thumb_url: data.thumb_url
        };
      }
    };
  }
})();
